package com.hy.domain.dto;

import com.hy.constans.HttpStatus;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
@AllArgsConstructor
public class R<T> {

    /** 成功 */
    public static final int SUCCESS = HttpStatus.SUCCESS;

    /** 失败 */
    public static final int FAIL = HttpStatus.ERROR;

    private int code;
    private T data;
    private String message;
    private Map map = null;

    public static <T> R<T> ok(T data) {
        final R<T> r = defaultOK();
        r.setData(data);
        return r;
    }

    private static <T> R<T> defaultOK() {
        return new R<T>(SUCCESS, null, "操作成功", null);
    }

    private static <T> R<T> defaultFail() {
        return new R<T>(FAIL, null, "操作失败", null);
    }

    public static <T> R<T> fail(String msg) {
        R r = defaultFail();
        r.setMessage(msg);
        return r;
    }

    public static <T> R<T> fail(Integer code, String msg) {
        return new R(code, null, msg, null);
    }

    public static R<String> ok() {
        return defaultOK();
    }

    public R<T> message(String message) {
        this.message = message;
        return this;
    }

    public static <T> R<T> by(boolean bool) {
        if (bool) {
            return defaultOK();
        } else {
            return defaultFail();
        }
    }

    public R<T> add(String key, Object value) {
        if (this.map == null) {
            map = new HashMap();
        }
        map.put(key, value);
        return this;
    }
}
